package com.meizhao.api.exception;


import com.meizhao.api.utils.HttpUtils;
import com.meizhao.api.utils.ResultCode;
import com.meizhao.api.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@ControllerAdvice
@Controller
@RequestMapping(value = "/error")
@ResponseBody
public class GlobalException implements ErrorController {

    private final MessageSource messageSource;

    @Autowired
    public GlobalException(MessageSource messageSource
                           ){
        this.messageSource = messageSource;
    }

    @ExceptionHandler
    public Object processException(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        if (e instanceof CommonException) {
            CommonException ce = (CommonException) e;
            return ResultUtils.result(ce.getCode(), null, ce.getMsg());
        }
        return ResultUtils.result(ResultCode.EXCEPTION, null, e.getMessage());
    }

    @Override
    public String getErrorPath() {

        return "error";
    }


    @RequestMapping
    public Object error(HttpServletRequest request) {

        if (HttpUtils.isAjax(request)) {
            return ResultUtils.result(ResultCode.ERROR, null, "Error");
        } else {
            ModelAndView modelAndView =  new ModelAndView(getErrorPath());
            modelAndView.addObject("base", HttpUtils.getContextUrl(request));
            return modelAndView;
        }
    }
}
